package action;

import info.NoNameInfo;
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import net.Connect;
import net.Process;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import start.Info;

public class GetNoNameList
{
  public static final String URL_GET_NONAME = Info.LoginServer + "/connect/app/menu/player_search?cyt=1";
  private static final String NONAME = "qX4A2VvX4pVwpgN63/NZrQ==";
  private static byte[] result;

  public static boolean run()
    throws Exception
  {
    ArrayList al = new ArrayList();
    al.add(new BasicNameValuePair("name", "qX4A2VvX4pVwpgN63/NZrQ=="));
    try {
      result = Process.connect.connectToServer(URL_GET_NONAME, al);
    } catch (Exception ex) {
      throw ex;
    }
    Document doc;
    try {
      doc = Process.ParseXMLBytes(result);
    }
    catch (Exception ex)
    {
      throw ex;
    }
    try
    {
      return parse(doc);
    } catch (Exception ex) {
      throw ex;
    }
  }

  private static boolean parse(Document doc) throws Exception {
    try {
      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();

      if (ExceptionCatch.catchException(doc)) {
        return false;
      }

      NodeList list = (NodeList)xpath.evaluate("/response/body/player_search/user_list/user[cost=25]", doc, XPathConstants.NODESET);
      NoNameInfo nameInfo = null;
      List nameInfos = new ArrayList();
      if (list.getLength() > 0) {
        for (int i = 0; i < list.getLength(); i++) {
          Node f = list.item(i).getFirstChild();
          nameInfo = new NoNameInfo();
          do {
            if (f.getNodeName().equals("id"))
              nameInfo.userId = f.getFirstChild().getNodeValue();
            else if (f.getNodeName().equals("cost")) {
              nameInfo.cost = Integer.parseInt(f.getFirstChild().getNodeValue());
            }
            f = f.getNextSibling();
          }while (f != null);
          nameInfos.add(nameInfo);
        }
      }
      Process.info.noNameList = nameInfos;
    } catch (Exception ex) {
      throw ex;
    }
    return true;
  }
}